package com.hatchsolution.ftp.factory;




import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import com.hatchsolution.ftp.exception.FTPClientException;
import com.hatchsolution.ftp.pool.FTPPoolConfig;




public class FTPClientFactory implements PooledObjectFactory<FTPClient> {
	private FTPPoolConfig config ;
	
	
	public FTPClientFactory(FTPPoolConfig config) {
		this.config = config;
	}
    
	
	
	public FTPClientFactory() {
	}



	@Override
	public void activateObject(PooledObject<FTPClient> pool) throws Exception {
	}

	@Override
	public void destroyObject(PooledObject<FTPClient>  pool) throws Exception {
		  FTPClient ftpClient = pool.getObject();  
		  if(ftpClient != null){
			  try {
				ftpClient.disconnect();
			} catch (Exception e) {
			    ftpClient = null ;
			}
		  }
	}

	@Override
	public PooledObject<FTPClient> makeObject() throws Exception {
		
		FTPClient ftpClient = new FTPClient();
		ftpClient.setConnectTimeout(config.getClientTimeout());
		ftpClient.connect(config.getHost(), config.getPort());
		int reply = ftpClient.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftpClient.disconnect();
			return null;
		}
		boolean result = ftpClient.login(config.getUsername(), config.getPassword());
		if (!result) {
			throw new FTPClientException(
					"ftpClient error userName:" + config.getUsername() + " ; password:" + config.getPassword());
		}
		ftpClient.setFileType(config.getTransferFileType());
		ftpClient.setBufferSize(1024);
		ftpClient.setControlEncoding(config.getEncoding());
		if (config.getPassiveMode() != null && config.getPassiveMode().equals("true")) {
			ftpClient.enterLocalPassiveMode();
		}

		return new DefaultPooledObject<FTPClient>(ftpClient);
	}

	

	@Override
	public boolean validateObject(PooledObject<FTPClient> pool) {
		FTPClient ftpClient = pool.getObject() ;
		try {
			return ftpClient != null && ftpClient.sendNoOp() ;
		} catch (IOException e) {
			return false;
		}
		
		
		
	}

	public void setConfig(FTPPoolConfig config) {
		this.config = config;
	}

	
	
	public FTPPoolConfig getConfig() {
		return config;
	}



	@Override
	public void passivateObject(PooledObject<FTPClient> p) throws Exception {
	}

	

	
	
}
